/**
 * 
 */
package com.cp16.tss.handler;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import com.cp16.tss.bo.CustomerBO;
import com.cp16.tss.bo.RequirementBO;
import com.cp16.tss.bo.ServiceBO;
import com.cp16.tss.common.Constants;
import com.cp16.tss.common.DateConvertUtil;
import com.cp16.tss.dto.Customer;
import com.cp16.tss.dto.Device;
import com.cp16.tss.dto.Phone;
import com.cp16.tss.dto.Requirement;
import com.cp16.tss.dto.Service;
import com.cp16.tss.form.RequirementAddNewForm;
import com.cp16.tss.form.RequirementEditForm;
import com.cp16.tss.form.RequirementForm;
import com.cp16.tss.validation.RequirementValidation;

/**
 * @author ADMIN
 * 
 */
public class RequirementHandler {

	RequirementBO requirementBO = new RequirementBO();
	CustomerBO customerBO = new CustomerBO();
	ServiceBO serviceBO = new ServiceBO();

	public void addNewRequirement(RequirementAddNewForm requirementAddNewForm) {
		if (RequirementValidation.validateRequirementAddNewForm(requirementAddNewForm)) {
			String customerId = requirementAddNewForm.getTxtCustomerId().getText();
			try {
				if (customerBO.checkCustomerExist(Integer.valueOf(customerId))) {
					try {
						Requirement requirement = new Requirement();
						// Customer of Requirement
						Customer customer = customerBO.getCustomerById(Integer.valueOf(customerId));
						String customerName = customer.getCustomerName();
						requirementAddNewForm.getTxtCustomerName().setText(customerName);
						requirement.setCustomer(customer);
						// Service of Requirement
						String serviceName = requirementAddNewForm.getCbService().getSelectedItem().toString();
						Service service = serviceBO.getServiceByName(serviceName);
						requirement.setService(service);
						// Date requirement
						Date dateRequirement = requirementAddNewForm.getTxtDateRequirement().getDate();
						requirement.setDateReq(dateRequirement);
						Date deadline = requirementAddNewForm.getTxtDeadLine().getDate();
						requirement.setDeadline(deadline);
						String status = requirementAddNewForm.getCbStatus().getSelectedItem().toString();
						requirement.setStatus(status);
						List<Phone> phoneList = getListPhone(requirementAddNewForm);
						requirement.setPhoneList(phoneList);
						List<Device> deviceList = getListDevice(requirementAddNewForm);
						requirement.setDeviceList(deviceList);
						requirementAddNewForm.getLblAddNewRequirement().setText("Add new requirement successfull");
						
						requirementBO.addNewRequirement(requirement);

					} catch (NumberFormatException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					requirementAddNewForm.getLblAddNewRequirement().setText("Customer ID not existed");
					return;
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public List<Requirement> getRequirementByCustomerId(int customerId) {
		List<Requirement> reqList = new ArrayList<Requirement>();
		reqList = requirementBO.getRequirementByCustomerId(customerId);
		return reqList;
	}

	@SuppressWarnings("unchecked")
	public void loadServiceNameToServiceComboBox(
			RequirementAddNewForm requirementAddNewForm) {
		try {
			List<Service> serviceList = serviceBO.getAllService();
			if (serviceList != null) {
				for (Service service : serviceList) {
					requirementAddNewForm.getCbService().addItem(
							service.getServiceName());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public List<Phone> getListPhone(RequirementAddNewForm requirementAddNewForm) {
		List<Phone> phoneList = new ArrayList<Phone>();
		String phoneText = requirementAddNewForm.getTxtPhoneList().getText();
		if(!phoneText.equals(Constants.BLANK)){
			if(phoneText.length() > 5){
				String charReplace = phoneText.substring(5, 6);
				phoneText = phoneText.replace(charReplace, Constants.BLANK);
			}
			int loopNumber = phoneText.toString().length()/5;
			int strBeginNumber = 0;
			Phone phone;
			String phoneNumber;
			for (int i = 0; i < loopNumber; i++) {
				phone = new Phone();
				strBeginNumber = 5*i; 
				phoneNumber = phoneText.substring(strBeginNumber, strBeginNumber + 5);
				phone.setPhoneNumber(Integer.valueOf(phoneNumber));
				phoneList.add(phone);
			}
		}

		return phoneList;
	}

	public List<Device> getListDevice(RequirementAddNewForm requirementAddNewForm){
		List<Device> deviceList = new ArrayList<Device>();
		if(requirementAddNewForm.getChckbxDeviceList().isSelected()){
			if(!requirementAddNewForm.getTxtDevice1().getText().equals(Constants.BLANK)){
				Device device1;
				device1 = new Device();
				device1.setDeviceName(requirementAddNewForm.getTxtDevice1().getText());
				device1.setDeviceAmount(Integer.valueOf(requirementAddNewForm.getTxtAmount1().getText()));
				device1.setDevicePrice(Integer.valueOf(requirementAddNewForm.getTxtPrice1().getText()));
				deviceList.add(device1);
			}
			
			if(!requirementAddNewForm.getTxtDevice2().getText().equals(Constants.BLANK)){
				Device device2;
				device2 = new Device();
				device2.setDeviceName(requirementAddNewForm.getTxtDevice2().getText());
				device2.setDeviceAmount(Integer.valueOf(requirementAddNewForm.getTxtAmount2().getText()));
				device2.setDevicePrice(Integer.valueOf(requirementAddNewForm.getTxtPrice2().getText()));
				deviceList.add(device2);
			}
			
			if(!requirementAddNewForm.getTxtDevice3().getText().equals(Constants.BLANK)){
				Device device3;
				device3 = new Device();
				device3.setDeviceName(requirementAddNewForm.getTxtDevice3().getText());
				device3.setDeviceAmount(Integer.valueOf(requirementAddNewForm.getTxtAmount3().getText()));
				device3.setDevicePrice(Integer.valueOf(requirementAddNewForm.getTxtPrice3().getText()));
				deviceList.add(device3);
			}
			
			if(!requirementAddNewForm.getTxtDevice4().getText().equals(Constants.BLANK)){
				Device device4;
				device4 = new Device();
				device4.setDeviceName(requirementAddNewForm.getTxtDevice4().getText());
				device4.setDeviceAmount(Integer.valueOf(requirementAddNewForm.getTxtAmount4().getText()));
				device4.setDevicePrice(Integer.valueOf(requirementAddNewForm.getTxtPrice4().getText()));
				deviceList.add(device4);
			}
			
			if(!requirementAddNewForm.getTxtDevice5().getText().equals(Constants.BLANK)){
				Device device5;
				device5 = new Device();
				device5.setDeviceName(requirementAddNewForm.getTxtDevice5().getText());
				device5.setDeviceAmount(Integer.valueOf(requirementAddNewForm.getTxtAmount5().getText()));
				device5.setDevicePrice(Integer.valueOf(requirementAddNewForm.getTxtPrice5().getText()));
				deviceList.add(device5);
			}
			
		}
		
		return deviceList;
	}

	public void doClearRequirementAddNewForm(RequirementAddNewForm requirementAddNewForm) {
		requirementAddNewForm.getLblAddNewRequirement().setText("Add new a requirement");
		requirementAddNewForm.getTxtCustomerId().setText(Constants.BLANK);
		requirementAddNewForm.getTxtCustomerName().setText(Constants.BLANK);
		requirementAddNewForm.getTxtDateRequirement().setDate(null);
		requirementAddNewForm.getTxtDeadLine().setDate(null);
		requirementAddNewForm.getTxtPhoneList().setText(Constants.BLANK);
		requirementAddNewForm.getChckbxDeviceList().setSelected(false);
		doSomethingWhenCheck(requirementAddNewForm);
		requirementAddNewForm.getTxtDevice1().setText(Constants.BLANK);
		requirementAddNewForm.getTxtDevice2().setText(Constants.BLANK);
		requirementAddNewForm.getTxtDevice3().setText(Constants.BLANK);
		requirementAddNewForm.getTxtDevice4().setText(Constants.BLANK);
		requirementAddNewForm.getTxtDevice5().setText(Constants.BLANK);
		requirementAddNewForm.getTxtAmount1().setText(Constants.BLANK);
		requirementAddNewForm.getTxtAmount2().setText(Constants.BLANK);
		requirementAddNewForm.getTxtAmount3().setText(Constants.BLANK);
		requirementAddNewForm.getTxtAmount4().setText(Constants.BLANK);
		requirementAddNewForm.getTxtAmount5().setText(Constants.BLANK);
		requirementAddNewForm.getTxtPrice1().setText(Constants.BLANK);
		requirementAddNewForm.getTxtPrice2().setText(Constants.BLANK);
		requirementAddNewForm.getTxtPrice3().setText(Constants.BLANK);
		requirementAddNewForm.getTxtPrice4().setText(Constants.BLANK);
		requirementAddNewForm.getTxtPrice5().setText(Constants.BLANK);
	}

	public void doSomethingWhenCheck(RequirementAddNewForm requirementAddNewForm) {
		boolean chckbxDeviceList = requirementAddNewForm.getChckbxDeviceList().isSelected();
		if (chckbxDeviceList) {
			requirementAddNewForm.getPanelDevice().setVisible(true);
		} else {
			requirementAddNewForm.getPanelDevice().setVisible(false);
		}
	}
	
	@SuppressWarnings({ "unchecked"})
	public void loadTable(RequirementForm requirementForm) {
		DefaultTableModel defaultTableModel = (DefaultTableModel) requirementForm.getTblResultSearch().getModel();
		int resultRow = requirementForm.getTblResultSearch().getRowCount();
		for (int i = 0; i < resultRow; i++) {
			defaultTableModel.removeRow(0);
		}

		List<Requirement> requirementList;
		try {
			requirementList = requirementBO.getAllRequirement();
			if (requirementList != null) {
				for (Requirement requirement : requirementList) {
					@SuppressWarnings("rawtypes")
					Vector rowData = new Vector();
					rowData.add(requirementList.indexOf(requirement) + 1);
					rowData.add(requirement.getRequirementId());
					rowData.add(requirement.getCustomer().getCustomerId());
					rowData.add(requirement.getCustomer().getCustomerName());
					rowData.add(requirement.getService().getServiceName());
					rowData.add(DateConvertUtil.convertDateToStringddMMyyyyDash(requirement.getDateReq()));
					rowData.add(DateConvertUtil.convertDateToStringddMMyyyyDash(requirement.getDeadline()));
					rowData.add(requirement.getStatus());
					if(requirement.getDateHandOver() != null){
						rowData.add(DateConvertUtil.convertDateToStringddMMyyyyDash(requirement.getDateHandOver()));
					}
					
					defaultTableModel.addRow(rowData);
				}
			}
			requirementForm.getTblResultSearch().setModel(defaultTableModel);
			displayTotalRequirement(requirementForm);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public List<Requirement> getRequirementByCustomerId(RequirementForm requirementForm){
		String customerIdSearch = requirementForm.getTxtCustomerId().getText();
		int requirementListFormSize = requirementForm.getTblResultSearch().getRowCount();
		List<Integer> indexList = new ArrayList<Integer>();
		List<Requirement> requirementList = new ArrayList<Requirement>();
		for (int i = 0; i < requirementListFormSize; i++) {
			String cusIdForm = (String) requirementForm.getTblResultSearch().getValueAt(i, 1);
			if(!customerIdSearch.equals(Constants.BLANK) && !customerIdSearch.equals(cusIdForm)) {
				indexList.add(i);
			}
		}
		for (int i = 0; i < indexList.size(); i++) {
			int rowIndex = requirementForm.getTblResultSearch().convertRowIndexToModel(indexList.get(i)) - i;
			((DefaultTableModel) requirementForm.getTblResultSearch().getModel()).removeRow(rowIndex);
			requirementForm.getTblResultSearch().repaint();
		}
		displayTotalRequirement(requirementForm);
		doClearRequirementForm(requirementForm);
		return requirementList;
	}
	
	public List<Requirement> getRequirementByStatus(RequirementForm requirementForm){
		String statusSearch = requirementForm.getCbStatus().getSelectedItem().toString();
		int requirementListFormSize = requirementForm.getTblResultSearch().getRowCount();
		List<Integer> indexList = new ArrayList<Integer>();
		List<Requirement> requirementList = new ArrayList<Requirement>();
		for (int i = 0; i < requirementListFormSize; i++) {
			String statusForm = (String) requirementForm.getTblResultSearch().getValueAt(i, 6);
			if(!statusSearch.equals(Constants.BLANK) && !statusSearch.equals(statusForm)) {
				indexList.add(i);
			}
		}
		for (int i = 0; i < indexList.size(); i++) {
			int rowIndex = requirementForm.getTblResultSearch().convertRowIndexToModel(indexList.get(i)) - i;
			((DefaultTableModel) requirementForm.getTblResultSearch().getModel()).removeRow(rowIndex);
			requirementForm.getTblResultSearch().repaint();
		}
		displayTotalRequirement(requirementForm);
		doClearRequirementForm(requirementForm);
		return requirementList;
	}
	
	public void displayTotalRequirement(RequirementForm requirementForm){
		requirementForm.getLblTotalRequirement().setText("Total: " + requirementForm.getTblResultSearch().getRowCount() + " Requirements");
	}
	
	public void doClearRequirementForm(RequirementForm requirementForm){
		requirementForm.getTxtCustomerId().setText(Constants.BLANK);
		requirementForm.getTxtDateFrom().setDate(null);
		requirementForm.getTxtDateTo().setDate(null);
		requirementForm.getCbStatus().setSelectedIndex(0);
	}
	
	public void searchRequirements(RequirementForm requirementForm){
		String customerId = requirementForm.getTxtCustomerId().getText();
		String status = requirementForm.getCbStatus().getSelectedItem().toString();
		String radiobuttonChooser = requirementForm.getRdbDateChooser().getSelection().getSelectedObjects().toString();
		Date dateFrom = requirementForm.getTxtDateFrom().getDate();
		Date dateTo = requirementForm.getTxtDateTo().getDate();
		requirementBO.searchRequirements(requirementForm);

	}

	// TODO
	public void editRequirementForm(RequirementForm requirementForm) {
		RequirementEditForm requirementEditForm = new RequirementEditForm();
		int selectColumnsNo = requirementForm.getTblResultSearch().getSelectedRowCount();
		if (selectColumnsNo > 0) {
			int selectRow = requirementForm.getTblResultSearch().getSelectedRow();
			int rowIndex = requirementForm.getTblResultSearch().convertRowIndexToModel(selectRow);
			String reqId = String.valueOf(requirementForm.getTblResultSearch().getValueAt(rowIndex, 1));
			String cusId =  String.valueOf(requirementForm.getTblResultSearch().getValueAt(rowIndex, 2));
			String cusName = (String) requirementForm.getTblResultSearch().getValueAt(rowIndex, 3);
			String serviceName = (String) requirementForm.getTblResultSearch().getValueAt(rowIndex, 4);
			String dateReq = (String) requirementForm.getTblResultSearch().getValueAt(rowIndex, 5);
			String deadline = (String) requirementForm.getTblResultSearch().getValueAt(rowIndex, 6);
			String status = (String) requirementForm.getTblResultSearch().getValueAt(rowIndex, 7);
			String dateRelease = (String) requirementForm.getTblResultSearch().getValueAt(rowIndex, 8);

			requirementEditForm.getCbService().setSelectedItem(serviceName);
			requirementEditForm.getTxtCustomerId().setText(cusId);
			requirementEditForm.getTxtCustomerName().setText(cusName);
			requirementEditForm.getTxtDateRequirement().setDate(
					DateConvertUtil.convertStringDashddMMyyyyToDate(dateReq));
			requirementEditForm.getTxtDeadLine().setDate(
					DateConvertUtil.convertStringDashddMMyyyyToDate(deadline));
			requirementEditForm.getCbStatus().setSelectedItem(status);
			List<Phone> phoneList;
			try {
				phoneList = (List<Phone>) requirementBO.getRequirementById(Integer.valueOf(reqId)).getPhoneList();
				int phoneText;
				StringBuilder phoneBuilder = new StringBuilder();
				if(phoneList != null){
					for (int i = 0; i < phoneList.size(); i++) {
						phoneText = phoneList.get(i).getPhoneNumber();
						phoneBuilder.append(phoneText).append(";");
					}
				}
				requirementEditForm.getTxtPhoneList().setText(phoneBuilder.toString());
				List<Device> deviceList = new ArrayList<Device>();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void deleteRequirementFromTable(RequirementForm requirementForm) {
		int selectColumnsNo = requirementForm.getTblResultSearch().getSelectedRowCount();
		int[] rowColumnsSelected = requirementForm.getTblResultSearch().getSelectedRows();
		if (selectColumnsNo > 0) {
			int click = JOptionPane.showConfirmDialog(requirementForm,
					"Do you want to delete selected requirement?",
					"Confirm delete requirement", JOptionPane.YES_NO_OPTION);

			if (click == JOptionPane.YES_OPTION) {
				int rowIndex;
				int cellSelect;
				Requirement requirement;
				for (int i = 0; i < selectColumnsNo; i++) {
					rowIndex = requirementForm.getTblResultSearch().convertRowIndexToModel(rowColumnsSelected[i]) - i;
					cellSelect = (Integer) requirementForm.getTblResultSearch().getValueAt(rowIndex, 1);
					try {
						requirement = requirementBO.getRequirementById(cellSelect);
						if(requirement != null){
							if(requirementBO.deleteRequirement(requirement)){
								((DefaultTableModel) requirementForm.getTblResultSearch().getModel()).removeRow(rowIndex);
								requirementForm.getTblResultSearch().repaint();
								displayTotalRequirement(requirementForm);
							}
						}
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	
	
}
